﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DNA.Mvc.Exporting.Exporters
{
    public class FilesExporter : Exporter
    {
        public string Destination { get; set; }

        public override void Execute(ExportingContext context)
        {
            string vSrc = GetMatch<string>(context);
            string source = context.HttpContext.Server.MapPath(vSrc);
            string destination = vSrc.Replace("~/", "");
            string directory = context.Destination + (context.Destination.EndsWith("\\") ? "" : "\\") + "content\\" + destination;

            if (!string.IsNullOrEmpty(Destination))
            {
                if (Destination.StartsWith("~/"))
                    directory = context.HttpContext.Server.MapPath(Destination);
                else
                    directory = Destination;
            }

            ExportTo(context, source, directory);
        }

        protected void ExportTo(ExportingContext context, string source, string directory)
        {
            if (Path.HasExtension(source))
            {
                var destFileName = directory;
                if (!Path.HasExtension(directory))
                    destFileName = directory + "\\" + Path.GetFileName(directory);
                File.Copy(source, destFileName);
            }
            else
            {
                if (Directory.Exists(source))
                    FileUtility.CopyDirectory(source, directory);
            }

            var installerName = "files";
            if (!context.Installers.ContainsKey(installerName))
                context.Installers.Add(installerName, "");
        }
    }
}
